/*
 * Mensaje.cpp
 *
 *  Created on: 31/05/2011
 *      Author: wadi
 */

#include "message.h"


Message::Message()
: logger_(log4cxx::Logger::getLogger("common.comm.menssage"))
{
  reset();
}

Message::~Message()
{
}

bool Message::isComplete()
{
  bool completo = (size+5 <= (buffer.size()));
  LOG4CXX_TRACE(logger_, "Chequeando completo "<< (completo && sizeReaded) << " " << size+(unsigned int)5 << " " << buffer.size());

  return (completo && sizeReaded);
}
std::vector< char> Message::getBuffer()  {
  return buffer;
}
unsigned int Message::readInteger(int desde) {

  unsigned int tamanio = 0;
      tamanio = (tamanio << 8)+(int) ((unsigned char) buffer[desde + 3]);
      tamanio = (tamanio << 8)+(int) ((unsigned char) (buffer)[desde + 2]);
      tamanio = (tamanio << 8)+(int) ((unsigned char) (buffer)[desde + 1]);
      tamanio = (tamanio << 8)+(int) ((unsigned char) buffer[desde]);

//  tamanio = ( (buffer[desde]) + (buffer[desde+1] << 8) + (buffer[desde+2] << 16)  + (buffer[desde+3] << 24) );

  LOG4CXX_TRACE(logger_, "Tamanio "<< tamanio);


  return tamanio;
}

void Message::serializeSize() {
  buffer.push_back( (size & 0xff) );
  buffer.push_back( ((size >> 8) & 0xff) );
  buffer.push_back( ((size >> 16) & 0xff) );
  buffer.push_back( ((size >> 24) & 0xff) );
}

void Message::add(unsigned char* data, int hasta) {
  for (int i = 0; i < hasta; i++) {
      buffer.push_back((char) data[i]);
  }
  if (buffer.size() >= (unsigned int) 5 && !sizeReaded) {
      // Entonces leemos el tamanio total
      size = readInteger(1);
//      if(size>=100000){
//
//
//                    size = readInteger(0);
//
//          LOG4CXX_TRACE(logger_, "Parseado tamanio muy grande:" << size);
//      }
      sizeReaded=true;
      LOG4CXX_TRACE(logger_, "Parseado tamanio" << size);
  }
}

void Message::reset() {
  size = 0;

  buffer.clear();
  LOG4CXX_TRACE(logger_, "buffer size" << buffer.size());
  sizeReaded=false;
}
